package game;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class Client implements Subject{
	private Socket socket;
	private ObjectOutputStream outputStream;
	private ObjectInputStream inputStream;
	private ArrayList<Observer> observers;
	private Game game;
	
	
	public Client(Game game, String ip){
		this.observers = new ArrayList<Observer>();
		this.observers.add(game);
		this.game = game;
		
		try {
			this.socket = new Socket(ip, 5000);
			outputStream = new ObjectOutputStream(socket.getOutputStream());
			inputStream = new ObjectInputStream(socket.getInputStream());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public synchronized ArrayList<Player> getUpdatedPlayers(Player p){
		ArrayList<Player> players = null;
		try {			
			outputStream.writeObject(p);
			outputStream.flush();
			outputStream.reset();
			Object o = inputStream.readObject();
			if(o instanceof Players)
				players = ((Players)o).getPlayers();
				for(Player pl : players)
					System.out.print(pl + ", ");
				
				System.out.println();
	
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return players;
	}
	
	public synchronized ArrayList<Player> sendUpdate() {
		ArrayList<Player> players = getUpdatedPlayers(game.getMe());
		notifyObservers(players);
		return players;
	}

	@Override
	public void addObserver(Observer o) {
		this.observers.add(o);
		
	}

	@Override
	public void removeObserver(Observer o) {
		this.observers.remove(o);
		
	}

	@Override
	public void notifyObservers(ArrayList<Player> players) {
		for (Observer o: observers){
			o.update(players);
		}
	}	
}
